import type { 
    RouteRequest,
    RouteResponse,
} from '@/types/map';
import { getRoute } from '@/api/graphHopper';
import {getLayerByName} from '@/config/mapFunction'
import Feature from 'ol/Feature';
import LineString from 'ol/geom/LineString';

    // 请求路径数据
export  async function fetchRoute(start: number[], end: number[]): Promise<RouteResponse> {
    const requestBody: RouteRequest = {
        points: [start, end],
        profile: "car",
        elevation: true,
        instructions: true,
        locale: "zh_CN",
        points_encoded: false,
        points_encoded_multiplier: 1000000,
        details: ["road_class", "road_environment"],
        snap_preventions: ["ferry"],
        custom_model: {
            distance_influence: 15,
            priority: [{
                "if": "road_environment == FERRY",
                "multiply_by": "0.9"
            }],
            speed: [],
            areas: {
                type: "FeatureCollection",
                features: []
            }
        },
        "ch.disable": true,
        "alternative_route.max_paths": 3,
        algorithm: "alternative_route"
    };

    const response: any = await getRoute(requestBody);

    if (!(response.status === 200)) {
        throw new Error(`没有找到道路`);
    }
    return response;
}


     // 绘制路径
 export function drawRoute(context, response: any,layerName) {
    const routeLayer: any = getLayerByName(context,layerName);
    routeLayer?.getSource()?.clear();

    response.paths.forEach((path: any) => {
        path.points.coordinates = path.points.coordinates.map((coord: any) => {
            return [coord[0], coord[1]];
        });

        const routeFeature = new Feature({
            geometry: new LineString(path.points.coordinates),
            type: 'route',
            properties: {
                distance: path.distance,
                time: path.time
            }
        });

        routeLayer.getSource()?.addFeature(routeFeature);
    });
    console.log(routeLayer.getSource()?.getFeatures())
    // 自动缩放至路径范围
    const extent = routeLayer.getSource()?.getExtent();
    if (extent) {
        context.map?.getView().fit(extent, {
            padding: [50, 50, 50, 50],
            duration: 1000
        });
    }
}
